/**
 * 连接到mongodb
 * 使用mongoose而非mongodb中间件
 **/
var mongoose = require('mongoose');
var config = require('../config');

var host = config.database.mongodb.db_host,
    port = config.database.mongodb.db_port,
    username = config.database.mongodb.db_ak,
    password = config.database.mongodb.db_sk,
    dbName = config.database.mongodb.db_name,
    url = "mongodb://" + username + ":" + password + "@" + host + ":" + port + "/" + dbName;

if (config.debug) {
    url = "mongodb://" + host + ":" + port + "/" + dbName;
}

var count = 0;
var dbcon = null;
function getConnect() {
    var opts = {
        db: {
            native_parser: true
        },
        server: {
            poolSize: 5,//默认为5
            auto_reconnect: true
        },
        user: username,
        pass: password
    };
    (function connect() {
        mongoose.connect(url, opts);//一个数据库用connect,多个用createConnection
        dbcon = mongoose.connection;//获取Connection 连接对象
        dbcon.on('error', function (error) {
            console.log('connection error');
            dbcon.readyState = "disconnected";
            reConnect();
        });
        //监听关闭事件并重连
        dbcon.on('disconnected', function () {
            console.log('disconnected');
            dbcon.readyState = "disconnected";
            dbcon.close();
        });
        dbcon.on('close', function (err) {
            dbcon.readyState = "disconnected";
            reConnect();
            console.log('close-event-to-connect');
        });
        dbcon.on('connecting', function () {
            console.log('connecting');
        });
        dbcon.on('connected', function () {
            console.log('connected');
        });
        dbcon.on('disconnecting', function () {
            console.log('disconnecting');
        });
    })();//定义完自执行
    //connected
    function reConnect() {
        dbcon.on('close', function () {
            dbcon.open(host, dbName, port, opts, function () {
                console.log('closed-reconnect');
            });
        })
    }
}

exports.getConnect = getConnect;//包含到module.exports对象中,

exports.mongoose = mongoose;